import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Table, Divider, Button, Popconfirm } from 'antd';

import Form from '../components/SearchForm';
import CollectionCreateForm from '../components/FormItem';

import { checkInit } from '@/utils/util';
import { UmiComponentProps, BaseComponentProps } from '@/common/type';
import { KEYS_EDIT } from '../enum';

export interface P {
  list: {
    data: Array<any>;
    dataCnt: number;
  };
  match: any;

}

export interface State {
  current: number;
  visible: boolean;
  buildId: string;
  details: {
    id?: string;
    buildId?: string;
    floorPlan?: string;
    floorType?: number | string;
    floorName?: string;
  },
}

type Props = P & UmiComponentProps & BaseComponentProps;

const ONE_PAGE_SIZE = 10;

@connect(({ build_floor, loading, menu }) => ({
  list: build_floor.list || {},
  loading: loading.effects['build_floor/queryPage'],
  buttons: menu.buttons,
  cond: build_floor.cond || {},
}))
class BuildFloor extends Component<Props, State> {

  state = {
    current: 1,
    visible: false,
    buildId: this.props.match.params.id,
    details: null,
  }
  formRef: any;

  queryData(offset = 1, size = ONE_PAGE_SIZE) {
    const { dispatch } = this.props;
    const { buildId } = this.state;

    dispatch({
      type: 'build_floor/queryPage',
      payload: {
        buildId,
        pageNum: offset,
        pageSize: size,
      },
    });
  }

  initCurrent = () => {

    this.setState({
      current: 1
    })
  };

  componentDidMount() {
    const { dispatch, match } = this.props;
    const { params } = match;
    this.setState({
      buildId: params.id
    });
    checkInit() ? dispatch({ type: 'build_floor/initCond', payload: { buildId: params.id } }) : this.queryData()
  }

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond, match } = this.props;
    const { params } = match;
    cond.pageSize = pageSize;
    dispatch({ type: `build_floor/updateCond`, payload: { ...cond, buildId: params.id } }).then(() => {
      this.initCurrent()
    })
  }

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  handleCancel = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'upload/init' }).then(() => {
      this.setState({ visible: false, details: null })
    })
  };

  handleCreate = (v) => {
    const { form } = this.formRef.props;
    form.validateFields((err, values) => {
      const { dispatch } = this.props;
      if (err) return;

      const ans = {
        ...values,
        buildId: this.state.details.buildId,
        id: this.state.details.id,
        floorPlan: v,
      }

      dispatch({
        type: 'build_floor/update',
        payload: ans
      }).then(() => {
        this.setState({ visible: false, details: null }, () => form.resetFields());
        this.initCurrent()
      })
    });
  }

  handleEdit = (v) => {
    const items = {};

    KEYS_EDIT.forEach(item => {
      items[item] = v[item]
    })
    this.setState({ visible: true, details: items });
  }

  handleDeleteConfirm = (id, buildId) => {
    const { dispatch } = this.props
    dispatch({ type: 'build_floor/remove', payload: { id, buildId } })
  }

  render() {
    const { list, buttons, dispatch } = this.props;
    const { data = [], dataCnt } = list;

    const btnList = {};
    if (Array.isArray(buttons)) {
      buttons.forEach(item => {
        btnList[item.name] = item.name
      });
    }

    const ans = Array.isArray(data) && data.map((v, ind) => ({
      ...v,
      ind: ind + 1
    }))

    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      current: this.state.current,
      onChange: (current) => {
        this.setState({ current })
        this.queryData(current)
      },
    };

    const columns = [{
      title: '序号',
      dataIndex: 'ind',
      render: (text) => (<>{text < 10 ? `0${text}` : text}</>)
    }, {
      title: '系统编号',
      dataIndex: 'systemNo',
    }, {
      title: '楼层号',
      dataIndex: 'floorName',
    }, {
      title: '楼层类型',
      dataIndex: 'floorTypeName',
    }, {
      title: '平面图',
      dataIndex: 'floorPlan',
      render: (text, record) => {
        return (text ? <Link to={`/data/build_floor/${record.id}/floorPlan`}>查看</Link> : <></>)
      }
    }, {
      title: '所属消控室',
      dataIndex: 'fireRoomName',
    }, {
      title: '操作', key: 'x', render: (record, text, index) => {
        return (
          <div style={{ display: 'flex' }}>
            <a onClick={this.handleEdit.bind(this, record)}>编辑</a>
            <Divider type="vertical" />
            <Link style={{ marginRight: 15 }} to={`/data/build_floor_area/${record.id}`}>查看区域</Link>
            {/* <Popconfirm
              okText='确定'
              cancelText='取消'
              title={'是否删除'}
              onConfirm={this.handleDeleteConfirm.bind(this, record.id, record.buildId)}
            >
              <a>删除</a>
            </Popconfirm> */}
          </div>
        )
      }
    }];

    return (
      <>
        <Form current={this.state.current} initCurrent={this.initCurrent} buildId={this.state.buildId} />
        <Table
          columns={Array.isArray(data) && data[0] && data[0].count > 1 ? columns : [...columns.slice(0, 5), ...columns.slice(6)]}
          pagination={pagination}
          dataSource={ans}
          rowKey="id"
          loading={this.props.loading}
          bordered
        />
        <Button
          icon="rollback"
          style={{ marginLeft: '40px', marginTop: '-50px', float: 'left' }}
          onClick={() => {
            dispatch({ type: 'build_floor/insert' });
            window.history.back()
          }}
        >返回</Button>
        {
          this.state.details && <CollectionCreateForm
            wrappedComponentRef={this.saveFormRef}
            visible={this.state.details && this.state.visible}
            onCancel={this.handleCancel}
            onCreate={this.handleCreate}
            data={this.state.details}
          />
        }
      </>
    );
  }
}

export default BuildFloor;
